﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using FileHelpers;
using Model;
using Model.Static;

namespace Command.Commands
{
	public class SyncAchievementCriteriasCommand : BaseCommand<Options>
	{
		private readonly IRepository _repository;

		public SyncAchievementCriteriasCommand(IRepository repository)
		{
			_repository = repository;
		}

		protected override void InternalExecute(Options options)
		{
			var file = Path.Combine(Environment.CurrentDirectory, "Static\\Data\\AchievementCriteria.csv");
			var rows = new FileHelperEngine<AchievementCriteriaRecord> {Options = {IgnoreFirstLines = 1}}
				.ReadFile(file)
				.OrderBy(x => x.ExternalKey)
				.ToArray();
			foreach (var row in rows)
			{
				var theRow = row;
				var achievement = _repository.Query<AchievementCriteria>().FirstOrDefault(x => x.ExternalKey == theRow.ExternalKey);
				if (achievement == null)
				{
					achievement = new AchievementCriteria
					{
						ExternalKey = theRow.ExternalKey,
						Description = theRow.Name,
						Value = theRow.Value,
						Achievement = _repository.Query<Achievement>().FirstOrDefault(x => x.ExternalKey == theRow.ExternalAchievementKey)
					};
					Console.WriteLine("Creating Missing Achievement Criteria: {0}", achievement.Description);
					_repository.Save(achievement);
				}
			}
		}
	}
}